package fr.inserm.umr915.vcfannotator.bio;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.zip.GZIPInputStream;

public class RemoteUcscFastaSequenceProvider
	implements SequenceProvider
	{
	private String build;
	
	public RemoteUcscFastaSequenceProvider(String build)
		{
		this.build=build;
		}	
	
	@Override
	public GenomicSequence getGenomicSequence(String chrom) throws IOException
		{
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		URL url=new URL("http://hgdownload.cse.ucsc.edu/goldenPath/"+build+"/chromosomes/"+chrom+".fa.gz");
		InputStream in=new BufferedInputStream(new GZIPInputStream(url.openStream()));
		int c;
		while((c=in.read())!=-1)
			{
			if(!Character.isWhitespace(c)) break;
			}
		if((char)c!='>') throw new IOException("Expected a fasta header '>'");
		while((c=in.read())!=-1)
			{
			if(c=='\n') break;
			}
		byte array[]=new byte[100000];
		int nRead=0;
		while((nRead=in.read(array))!=-1)
			{
			for(int i=0;i< nRead;++i)
				{
				if(Character.isWhitespace(array[i])) continue;
				baos.write(Character.toUpperCase(array[i]));
				}
			}
		return new GenomicSequence(chrom, 0, baos.toByteArray());
		}
	
	@Override
	public GenomicSequence getGenomicSequence(
			String chrom,
			int chromStart0,
			int chromEnd0) throws IOException
		{
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		URL url=new URL("http://hgdownload.cse.ucsc.edu/goldenPath/"+build+"/chromosomes/"+chrom+".fa.gz");
		InputStream in=new BufferedInputStream(new GZIPInputStream(url.openStream()));
		int c;
		while((c=in.read())!=-1)
			{
			if(!Character.isWhitespace(c)) break;
			}
		if((char)c!='>') throw new IOException("Expected a fasta header '>'");
		while((c=in.read())!=-1)
			{
			if(c=='\n') break;
			}
		byte array[]=new byte[100000];
		int nRead=0;
		int nPos=-1;
		while((nRead=in.read(array))!=-1)
			{
			for(int i=0;i< nRead;++i)
				{
				if(Character.isWhitespace(array[i])) continue;
				++nPos;
				if(chromStart0<nPos) continue;
				baos.write(Character.toUpperCase(array[i]));
				if(nPos+1>=chromEnd0) break;;
				}
			}
		return new GenomicSequence(chrom,chromStart0, baos.toByteArray());
		}
	
	@Override
	public void close()
		{
		
		}
	}
